package com.bruce.controller;

import com.bruce.bean.Admin;
import com.bruce.service.AdminService;
import com.bruce.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 专门负责登录的控制器
 */
@WebServlet("/adminServlet.do")
public class AdminServlet extends HttpServlet {

    AdminService adminService=new AdminServiceImpl();

    /**
     * 无论是get 还是post 最终都执行doPost方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //执行业务逻辑
        String method=req.getParameter("flag");
        HttpSession session = req.getSession();
        String syscode=(String) session.getAttribute("syscode"); //系统生成验证码
        if ("login".equals(method)){
            Admin_login(req, resp, method, session, syscode);
        }else if("logout".equals(method)){
            admin_logout(resp, session);
        }

    }

    private void Admin_login(HttpServletRequest req, HttpServletResponse resp, String method, HttpSession session, String syscode) throws IOException, ServletException {
        if("login".equals(method)){
            //管理员登录
            String aname = req.getParameter("aname");
            String apassword = req.getParameter("apassword");
            String usercode = req.getParameter("usercode"); //用户输入的验证码
            if(syscode.equalsIgnoreCase(usercode)){
                //封装登录对象
                Admin admin=new Admin(aname,apassword);
                //调用登录方法
                Admin adminLogin = adminService.adminLogin(admin);
                if(adminLogin!=null){
                    //登录成功，跳转首页
                    session.setAttribute("aname",admin.getAname());
                    resp.sendRedirect("/admin/adminFace.jsp");
                }else{
                    //登录失败(转发，存值。共享request中的值) 存值！
                    req.setAttribute("msg","账号或密码错误！");
                    req.setAttribute("role","admin");
                    req.getRequestDispatcher("login.jsp").forward(req,resp);
                }
            }else{
                req.setAttribute("msg","验证码错误！");
                req.setAttribute("role","admin");
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }
        }
    }

    private void admin_logout(HttpServletResponse resp, HttpSession session) throws IOException {
        session.invalidate();
        ;
        resp.sendRedirect("/login.jsp");
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }


}
